package com.cindata.api

import grails.converters.JSON
import grails.transaction.Transactional
import groovy.json.JsonOutput
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import groovy.util.slurpersupport.GPathResult
import groovyx.net.http.ContentType
import groovyx.net.http.FromServer

//import groovyx.net.http.HTTPBuilder
import groovyx.net.http.HttpBuilder
import groovyx.net.http.Method
import groovyx.net.http.Method.*
import groovyx.net.http.ContentType.*
import groovyx.net.http.OkHttpBuilder
import groovyx.net.http.RESTClient
import okhttp3.OkHttpClient
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Value

import java.util.concurrent.TimeUnit

class ApiService implements InitializingBean
{

    static scope = "singleton"
    OkHttpBuilder http

    @Value('${api.address}')
    String apiAddress
    @Value('${api.context}')
    String context
    @Value('${api.key}')
    String apiKey
    @Value('${api.evaluate}')
    String evaluateAPI
    @Value('${assessApi.key}')
    String assessApiKey
    @Value('${assessApi.assess}')
    String assessAPI
    @Value('${api.community}')
    String communityAPI
    @Value('${api.building}')
    String buildingAPI
    @Value('${api.unit}')
    String unitAPI
    @Value('${api.house}')
    String houseAPI
    @Value('${api.sale}')
    String saleAPI
    @Value('${api.listing}')
    String listingAPI
    @Value('${api.picture}')
    String pictureAPI
    @Value('${api.top5PriceTrend}')
    String top5PriceTrendAPI
    @Value('${api.standardPrice}')
    String standardPriceAPI
    @Value('${api.likeCommunity}')
    String likeCommunityAPI
    @Value('${api.communityRate}')
    String communityRateAPI
    @Value('${api.communityLastMonthData}')
    String communityLastMonthDataAPI
    @Value('${api.searchCompany}')
    String searchCompanyAPI
    @Value('${api.getCompanyInfo}')
    String getCompanyInfoAPI
    @Value('${api.getCompanyProject}')
    String getCompanyProjectAPI

    /**
     * 评估
     * @param data
     * @return
     */
    def evaluate(Map data)
    {
        def result
        try
        {
            result = post(evaluateAPI, data)
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    def assess(Map data)
    {
        def result
        try
        {
            result = post1(assessAPI, data)
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 获取小区信息
     * @param city
     * @param id
     * @return
     */
    def community(String city, Long id)
    {
        def result
        try
        {
            result = post(communityAPI, [communityId: id, cityCode: city])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 获取小区列表
     * @param city
     * @param id
     * @return
     */
    def communityList(String city, String district, String communityName, int limit)
    {
        def result
        try
        {
            if (district && district != "-1")
            {
                result = post(likeCommunityAPI, [cityCode: city, districtCode: district, name: communityName, limit: limit])
            }
            else
            {
                result = post(likeCommunityAPI, [cityCode: city, name: communityName, limit: limit])
            }

        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 获取成交案例列表
     * @param city
     * @param communityId
     * @return
     */
    def sale(String city, Long communityId)
    {
        def result
        try
        {
            result = post(saleAPI, [communityId: communityId, cityCode: city])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 获取挂牌案例列表
     * @param city
     * @param communityId
     * @return
     */
    def listing(String city, Long communityId)
    {
        def result
        try
        {
            result = post(listingAPI, [communityId: communityId, cityCode: city])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [],
                message: ex.getMessage()]
        }
        return result
    }

    def building(String city, Long communityId, String name)
    {
        def result
        try
        {
            result = post(buildingAPI, [cityCode: city, communityId: communityId, buildingName: name])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    def unit(String city, Long communityId, Long buildingId, String name)
    {
        def result
        try
        {
            result = post(unitAPI, [cityCode: city, communityId: communityId, buildingId: buildingId, unitName: name])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    def house(String city, Long buildingId, Long unitId, String name)
    {
        def result
        try
        {
            result = post(houseAPI, [cityCode: city, buildingId: buildingId, unitId: unitId, house: name])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /*
    * 获得图片的API
    */

    def picture(String city, Long addressId, Long addrTypeCd, Long limit)
    {
        def result
        try
        {
            result = post(pictureAPI, [cityCode: city, addressId: addressId, addrTypeCd: addrTypeCd, limit: limit])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 获取top5小区价格分布
     * @param data
     * @return
     */
    def top5PriceTrend(String city)
    {
        def result
        try
        {
            result = post(top5PriceTrendAPI, [cityCode: city])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 批量获取小区基准价
     * @param data
     * @return
     */
    def standardPrice(String city, String ids)
    {
        def result
        try
        {
            result = post(standardPriceAPI, [cityCode: city, ids: ids])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 小区走势
     * @param data
     * @return
     */
    def communityRate(String city, String communityId)
    {
        def result
        try
        {
            result = post(communityRateAPI, [cityCode: city, communityId: communityId])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 当月价格
     * @param data
     * @return
     */
    def communityLastMonthData(String city, String communityId)
    {
        def result
        try
        {
            result = post(communityLastMonthDataAPI, [cityCode: city, communityId: communityId])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 开发商搜索
     * @param ScompanyName
     * @param limit
     */
    def searchCompany(String companyName, int limit)
    {
        def result
        try
        {
            result = post(searchCompanyAPI, [companyName: companyName, limit: limit])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 开发商信息
     * @param companyId
     */
    def getCompanyInfo(String companyId)
    {
        def result
        try
        {
            result = post(getCompanyInfoAPI, [companyId: companyId])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    /**
     * 开发商项目
     * @param companyId
     * @param pageNo
     * @param pageCount
     */
    def getCompanyProject(String companyId, int pageNo, int pageCount)
    {
        def result
        try
        {
            result = post(getCompanyProjectAPI, [companyId: companyId, pageNo: pageNo, pageCount: pageCount])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [:],
                message: ex.getMessage()]
        }
        return result
    }

    @Override
    void afterPropertiesSet() throws Exception
    {
        http = OkHttpBuilder.configure {
            request.uri = apiAddress
            // request.headers["Cache-Control"] = ["no-cache"]
            client.clientCustomizer { OkHttpClient.Builder builder ->
                builder.connectTimeout(10, TimeUnit.SECONDS)
                builder.readTimeout(20, TimeUnit.SECONDS)
            }
        }
    }

    def post(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${context}${url}"
                request.uri.query = [key: apiKey]
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                log.info("--------------------->准备API请求，地址：${request.uri.path},key：${request.uri.query}")
                log.info("--------------------->准备API请求，参数：${JsonOutput.toJson(request.body).toString()}")
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def post1(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${context}${url}"
                request.uri.query = [key: assessApiKey]
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                log.info("--------------------->准备API请求，地址：${request.uri.path},key：${request.uri.query}")
                log.info("--------------------->准备API请求，参数：${JsonOutput.toJson(request.body).toString()}")
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println "Assess statusCode: " + resp.statusCode
                    println "Assess resultValue: " + JSON.parse(json.toString())
                    return JSON.parse(json.toString())
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def get(String url, Map data)
    {
        try
        {
            http.get {
                request.uri.path = "${context}${url}"
                request.uri.query = [key: apiKey]
                request.contentType = ContentType.JSON
                data?.each { key, value -> request.uri.query[key] = value
                }
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { FromServer resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }
}
